<template>
  <div class="game-app">
    <!-- 顶部信息栏 -->
    <div class="info-bar">
      <div class="info-item">
        <span class="label">得分显示：</span>
        <span class="value">Score: {{ score }}</span>
      </div>
      <div class="info-item">
        <span class="label">生命值：</span>
        <span class="value">Lives: {{ lives }}</span>
        <span class="hearts">❤️❤️❤️</span>
      </div>
      <div class="info-item">
        <span class="label">本地最高分：</span>
        <span class="value">High Score: {{ highScore }}</span>
      </div>
    </div>
    
    <!-- 游戏主画布 -->
    <div class="game-canvas" ref="gameCanvas">
      <!-- 火焰弹球 -->
      <div 
        class="ball" 
        :class="{ 'fire-effect': isFireMode }"
        :style="{
          left: `${ball.x}px`,
          top: `${ball.y}px`
        }"
      >
        <div v-if="isFireMode" class="fire-particles">
          <div v-for="particle in fireParticles" :key="particle.id" class="particle" :style="particle.style"></div>
        </div>
      </div>
      
      <!-- 挡板 -->
      <div 
        class="paddle" 
        :style="{
          left: `${paddle.x}px`,
          top: `${paddle.y}px`
        }"
      ></div>
      
      <!-- 砖块 -->
      <div 
        v-for="(brick, index) in bricks" 
        :key="index" 
        v-if="brick.health > 0"
        class="brick" 
        :class="getBrickClass(brick.health)"
        :style="{
          left: `${brick.x}px`,
          top: `${brick.y}px`,
          width: `${brickWidth}px`,
          height: `${brickHeight}px`
        }"
      ></div>
    </div>
    
    <!-- 底部控制栏 -->
    <div class="control-bar">
      <button class="control-btn restart" @click="restartGame">🔄 重新开始</button>
      <button class="control-btn pause" @click="togglePause">
        {{ isPaused ? '▶️ 继续' : '⏸️ 暂停' }}
      </button>
      <div class="instructions">
        鼠标/键盘←→控制挡板
      </div>
    </div>
    
    <!-- 游戏结束/开始界面 -->
    <div v-if="showStartScreen || isGameOver" class="overlay">
      <div class="overlay-content">
        <h2 v-if="showStartScreen">火焰弹球打砖块</h2>
        <h2 v-else>游戏结束！</h2>
        <p v-if="showStartScreen">点击开始按钮开始游戏</p>
        <p v-else>你的得分：{{ score }}</p>
        <p v-if="isNewRecord" class="new-record">新纪录！🏆</p>
        <button class="start-btn" @click="startGame">开始游戏</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GameApp',
  data() {
    return {
      // 游戏状态
      score: 0,
      lives: 3,
      highScore: 0,
      isPaused: false,
      showStartScreen: true,
      isGameOver: false,
      isNewRecord: false,
      
      // 游戏元素
      ball: {
        x: 0,
        y: 0,
        radius: 10,
        dx: 5,
        dy: -5
      },
      paddle: {
        x: 0,
        y: 0,
        width: 100,
        height: 20
      },
      bricks: [],
      brickWidth: 90,
      brickHeight: 30,
      brickRows: 5,
      brickCols: 8,
      brickPadding: 5,
      brickOffsetTop: 20,
      brickOffsetLeft: 35,
      
      // 火焰特效
      isFireMode: false,
      fireModeTimer: 0,
      fireParticles: [],
      
      // 游戏画布
      canvasWidth: 800,
      canvasHeight: 600,
      
      // 控制状态
      leftPressed: false,
      rightPressed: false,
      
      // 游戏循环
      gameLoopId: null
    }
  },
  mounted() {
    this.loadHighScore()
    this.initializeBricks()
    this.resetPaddleAndBall()
    
    // 绑定事件监听器
    window.addEventListener('keydown', this.handleKeyDown)
    window.addEventListener('keyup', this.handleKeyUp)
    this.$refs.gameCanvas.addEventListener('mousemove', this.handleMouseMove)
  },
  beforeUnmount() {
    // 清理事件监听器和游戏循环
    window.removeEventListener('keydown', this.handleKeyDown)
    window.removeEventListener('keyup', this.handleKeyUp)
    this.$refs.gameCanvas.removeEventListener('mousemove', this.handleMouseMove)
    if (this.gameLoopId) {
      cancelAnimationFrame(this.gameLoopId)
    }
  },
  methods: {
    // 初始化砖块
    initializeBricks() {
      this.bricks = []
      for (let row = 0; row < this.brickRows; row++) {
        for (let col = 0; col < this.brickCols; col++) {
          const brickX = col * (this.brickWidth + this.brickPadding) + this.brickOffsetLeft
          const brickY = row * (this.brickHeight + this.brickPadding) + this.brickOffsetTop
          // 根据行数决定砖块生命值：红色1血、黄色2血、绿色3血
          let health = 1
          if (row < 1) health = 1 // 第1行：红色
          else if (row < 3) health = 2 // 第2-3行：黄色
          else health = 3 // 第4-5行：绿色
          
          this.bricks.push({
            x: brickX,
            y: brickY,
            health: health
          })
        }
      }
    },
    
    // 重置挡板和球的位置
    resetPaddleAndBall() {
      // 挡板居中
      this.paddle.x = (this.canvasWidth - this.paddle.width) / 2
      this.paddle.y = this.canvasHeight - 50
      
      // 球在挡板上方居中
      this.ball.x = this.paddle.x + this.paddle.width / 2 - this.ball.radius
      this.ball.y = this.paddle.y - this.ball.radius * 2
      
      // 重置球速
      this.ball.dx = 5
      this.ball.dy = -5
      
      // 重置火焰模式
      this.isFireMode = false
      this.fireModeTimer = 0
      this.fireParticles = []
    },
    
    // 开始游戏
    startGame() {
      this.showStartScreen = false
      this.isGameOver = false
      this.isNewRecord = false
      this.resetGame()
      this.startGameLoop()
    },
    
    // 重置游戏
    resetGame() {
      this.score = 0
      this.lives = 3
      this.isPaused = false
      this.initializeBricks()
      this.resetPaddleAndBall()
    },
    
    // 重启游戏
    restartGame() {
      this.stopGameLoop()
      this.resetGame()
      if (!this.showStartScreen) {
        this.startGameLoop()
      }
    },
    
    // 暂停/继续游戏
    togglePause() {
      if (this.isGameOver || this.showStartScreen) return
      
      this.isPaused = !this.isPaused
      if (this.isPaused) {
        this.stopGameLoop()
      } else {
        this.startGameLoop()
      }
    },
    
    // 开始游戏循环
    startGameLoop() {
      this.gameLoop()
    },
    
    // 停止游戏循环
    stopGameLoop() {
      if (this.gameLoopId) {
        cancelAnimationFrame(this.gameLoopId)
        this.gameLoopId = null
      }
    },
    
    // 游戏主循环
    gameLoop() {
      if (!this.isPaused && !this.isGameOver && !this.showStartScreen) {
        this.update()
        this.checkCollisions()
        this.checkGameOver()
        this.updateFireEffect()
      }
      
      this.gameLoopId = requestAnimationFrame(this.gameLoop)
    },
    
    // 更新游戏状态
    update() {
      // 更新挡板位置
      this.updatePaddle()
      
      // 更新球位置
      this.ball.x += this.ball.dx
      this.ball.y += this.ball.dy
    },
    
    // 更新挡板位置
    updatePaddle() {
      // 键盘控制
      if (this.leftPressed && this.paddle.x > 0) {
        this.paddle.x -= 10
      }
      if (this.rightPressed && this.paddle.x < this.canvasWidth - this.paddle.width) {
        this.paddle.x += 10
      }
    },
    
    // 检查碰撞
    checkCollisions() {
      // 球与墙壁碰撞
      this.checkWallCollisions()
      
      // 球与挡板碰撞
      this.checkPaddleCollision()
      
      // 球与砖块碰撞
      this.checkBrickCollisions()
    },
    
    // 检查墙壁碰撞
    checkWallCollisions() {
      // 左右墙壁
      if (this.ball.x <= 0 || this.ball.x >= this.canvasWidth - this.ball.radius * 2) {
        this.ball.dx = -this.ball.dx
        this.ball.x = this.ball.x <= 0 ? 0 : this.canvasWidth - this.ball.radius * 2
      }
      
      // 上墙壁
      if (this.ball.y <= 0) {
        this.ball.dy = -this.ball.dy
        this.ball.y = 0
      }
      
      // 下墙壁（失球）
      if (this.ball.y >= this.canvasHeight) {
        this.lives--
        if (this.lives > 0) {
          this.resetPaddleAndBall()
        } else {
          this.gameOver()
        }
      }
    },
    
    // 检查挡板碰撞
    checkPaddleCollision() {
      if (
        this.ball.y + this.ball.radius * 2 >= this.paddle.y &&
        this.ball.y + this.ball.radius * 2 <= this.paddle.y + this.paddle.height &&
        this.ball.x + this.ball.radius * 2 >= this.paddle.x &&
        this.ball.x <= this.paddle.x + this.paddle.width
      ) {
        // 反弹
        this.ball.dy = -Math.abs(this.ball.dy)
        
        // 根据碰撞位置调整水平速度
        const hitPos = (this.ball.x + this.ball.radius) - (this.paddle.x + this.paddle.width / 2)
        const hitRatio = hitPos / (this.paddle.width / 2)
        this.ball.dx = hitRatio * 8 // 最大水平速度为8
      }
    },
    
    // 检查砖块碰撞
    checkBrickCollisions() {
      for (let i = 0; i < this.bricks.length; i++) {
        const brick = this.bricks[i]
        if (brick.health > 0) {
          if (
            this.ball.x + this.ball.radius * 2 >= brick.x &&
            this.ball.x <= brick.x + this.brickWidth &&
            this.ball.y + this.ball.radius * 2 >= brick.y &&
            this.ball.y <= brick.y + this.brickHeight
          ) {
            // 反弹
            this.ball.dy = -this.ball.dy
            
            // 减少砖块生命值
            if (this.isFireMode) {
              // 火焰模式下直接摧毁砖块
              this.bricks[i].health = 0
              this.score += brick.health * 100
            } else {
              this.bricks[i].health--
              this.score += 100
            }
            
            // 随机触发火焰模式
            if (Math.random() < 0.1) {
              this.activateFireMode()
            }
            
            break
          }
        }
      }
    },
    
    // 激活火焰模式
    activateFireMode() {
      this.isFireMode = true
      this.fireModeTimer = 100 // 火焰模式持续的帧数
    },
    
    // 更新火焰特效
    updateFireEffect() {
      if (this.isFireMode) {
        this.fireModeTimer--
        
        // 更新粒子
        this.updateParticles()
        
        // 创建新粒子
        this.createFireParticles()
        
        // 检查火焰模式是否结束
        if (this.fireModeTimer <= 0) {
          this.isFireMode = false
          this.fireParticles = []
        }
      }
    },
    
    // 创建火焰粒子
    createFireParticles() {
      for (let i = 0; i < 3; i++) {
        const angle = Math.PI + Math.random() * Math.PI
        const speed = 1 + Math.random() * 3
        const size = 2 + Math.random() * 4
        
        this.fireParticles.push({
          id: Date.now() + i,
          x: this.ball.x + this.ball.radius,
          y: this.ball.y + this.ball.radius,
          vx: Math.cos(angle) * speed,
          vy: Math.sin(angle) * speed,
          size: size,
          life: 30 + Math.random() * 20,
          style: {
            left: `${this.ball.x + this.ball.radius}px`,
            top: `${this.ball.y + this.ball.radius}px`,
            width: `${size}px`,
            height: `${size}px`,
            opacity: 1
          }
        })
      }
      
      // 限制粒子数量
      if (this.fireParticles.length > 100) {
        this.fireParticles = this.fireParticles.slice(-100)
      }
    },
    
    // 更新粒子
    updateParticles() {
      this.fireParticles = this.fireParticles.filter(particle => {
        particle.x += particle.vx
        particle.y += particle.vy
        particle.life--
        particle.style = {
          left: `${particle.x}px`,
          top: `${particle.y}px`,
          width: `${particle.size}px`,
          height: `${particle.size}px`,
          opacity: particle.life / 50
        }
        return particle.life > 0
      })
    },
    
    // 检查游戏结束
    checkGameOver() {
      // 检查所有砖块是否被摧毁
      const activeBricks = this.bricks.filter(brick => brick.health > 0)
      if (activeBricks.length === 0) {
        // 所有砖块被摧毁，游戏胜利
        this.score += 5000 // 额外奖励
        this.checkHighScore()
        this.isGameOver = true
        this.stopGameLoop()
      }
      
      // 检查生命值是否为0
      if (this.lives <= 0) {
        this.gameOver()
      }
    },
    
    // 游戏结束
    gameOver() {
      this.isGameOver = true
      this.checkHighScore()
      this.stopGameLoop()
    },
    
    // 检查是否创造新纪录
    checkHighScore() {
      if (this.score > this.highScore) {
        this.highScore = this.score
        this.isNewRecord = true
        this.saveHighScore()
      }
    },
    
    // 保存最高分
    saveHighScore() {
      try {
        localStorage.setItem('brickBreakerHighScore', this.highScore.toString())
      } catch (e) {
        console.warn('无法保存最高分')
      }
    },
    
    // 加载最高分
    loadHighScore() {
      try {
        const saved = localStorage.getItem('brickBreakerHighScore')
        this.highScore = saved ? parseInt(saved, 10) : 1200
      } catch (e) {
        this.highScore = 1200 // 默认最高分为1200
      }
    },
    
    // 获取砖块样式类
    getBrickClass(health) {
      switch (health) {
        case 1:
          return 'brick-red'
        case 2:
          return 'brick-yellow'
        case 3:
          return 'brick-green'
        default:
          return ''
      }
    },
    
    // 键盘按下事件处理
    handleKeyDown(event) {
      if (event.key === 'ArrowLeft') {
        this.leftPressed = true
      } else if (event.key === 'ArrowRight') {
        this.rightPressed = true
      } else if (event.key === ' ') {
        // 空格键暂停/继续
        this.togglePause()
      }
    },
    
    // 键盘松开事件处理
    handleKeyUp(event) {
      if (event.key === 'ArrowLeft') {
        this.leftPressed = false
      } else if (event.key === 'ArrowRight') {
        this.rightPressed = false
      }
    },
    
    // 鼠标移动事件处理
    handleMouseMove(event) {
      if (this.isPaused || this.isGameOver || this.showStartScreen) return
      
      const canvasRect = this.$refs.gameCanvas.getBoundingClientRect()
      const relativeX = event.clientX - canvasRect.left
      
      if (relativeX > 0 && relativeX < this.canvasWidth) {
        this.paddle.x = relativeX - this.paddle.width / 2
        // 限制挡板在画布内
        if (this.paddle.x < 0) {
          this.paddle.x = 0
        }
        if (this.paddle.x > this.canvasWidth - this.paddle.width) {
          this.paddle.x = this.canvasWidth - this.paddle.width
        }
      }
    }
  }
}
</script>

<style scoped>
.game-app {
  width: 100%;
  display: flex;
  flex-direction: column;
}

/* 顶部信息栏 */
.info-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #333;
  color: white;
  font-size: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-item .label {
  color: #aaa;
}

.info-item .value {
  font-weight: bold;
  color: #fff;
}

.hearts {
  font-size: 18px;
  letter-spacing: 2px;
}

/* 游戏主画布 */
.game-canvas {
  position: relative;
  width: 100%;
  height: 600px;
  background-color: #000;
  overflow: hidden;
  cursor: none;
}

/* 火焰弹球 */
.ball {
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #ff3333;
  box-shadow: 0 0 10px rgba(255, 51, 51, 0.8);
  transition: background-color 0.3s;
}

.ball.fire-effect {
  background-color: #ff6600;
  box-shadow: 0 0 20px rgba(255, 102, 0, 1);
  animation: firePulse 0.3s infinite alternate;
}

@keyframes firePulse {
  from { transform: scale(1); }
  to { transform: scale(1.1); }
}

/* 火焰粒子 */
.fire-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.particle {
  position: absolute;
  background-color: #ffcc00;
  border-radius: 50%;
  pointer-events: none;
}

/* 挡板 */
.paddle {
  position: absolute;
  width: 100px;
  height: 20px;
  background-color: #3366ff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(51, 102, 255, 0.8);
}

/* 砖块 */
.brick {
  position: absolute;
  border-radius: 5px;
  transition: background-color 0.2s, transform 0.1s;
}

.brick-red {
  background-color: #ff3333;
  box-shadow: 0 0 10px rgba(255, 51, 51, 0.6);
}

.brick-yellow {
  background-color: #ffcc00;
  box-shadow: 0 0 10px rgba(255, 204, 0, 0.6);
}

.brick-green {
  background-color: #33cc33;
  box-shadow: 0 0 10px rgba(51, 204, 51, 0.6);
}

.brick:hover {
  transform: scale(1.02);
}

/* 底部控制栏 */
.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f0f0f0;
  border-top: 1px solid #ddd;
}

.control-btn {
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.1s;
}

.restart {
  background-color: #33cc33;
  color: white;
}

.restart:hover {
  background-color: #2eb82e;
  transform: scale(1.05);
}

.pause {
  background-color: #ff9900;
  color: white;
}

.pause:hover {
  background-color: #e68a00;
  transform: scale(1.05);
}

.instructions {
  font-size: 14px;
  color: #666;
}

/* 游戏结束/开始界面 */
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.overlay-content {
  text-align: center;
  color: white;
  background-color: rgba(50, 50, 50, 0.9);
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
}

.overlay-content h2 {
  font-size: 32px;
  margin-bottom: 20px;
  color: #ff6600;
}

.overlay-content p {
  font-size: 18px;
  margin-bottom: 15px;
}

.new-record {
  color: #ffcc00;
  font-size: 24px !important;
  font-weight: bold;
  animation: glow 1s infinite alternate;
}

@keyframes glow {
  from { text-shadow: 0 0 10px #ffcc00; }
  to { text-shadow: 0 0 20px #ffcc00, 0 0 30px #ffcc00; }
}

.start-btn {
  margin-top: 20px;
  padding: 15px 30px;
  font-size: 18px;
  background-color: #ff6600;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s;
}

.start-btn:hover {
  background-color: #ff8533;
  transform: scale(1.1);
}

/* 响应式设计 */
@media (max-width: 800px) {
  .game-canvas {
    height: 500px;
  }
  
  .info-bar {
    font-size: 14px;
    padding: 10px;
  }
  
  .control-bar {
    flex-direction: column;
    gap: 10px;
  }
}
</style>